import {type Color, Material, Scene} from "three";
import {ModelLoadable} from "../../framework/model/ModelLoadable.ts";



export class Reactor extends ModelLoadable {

    private changeColor = 0
    private alarmTimer: number = 0
    private statusMaterial!: Material
    private status = 1 // 1: idle, 2: work, 3: alarm
    constructor() {
        super("reactor", "gltf", "models/industry/v1/reactor.glb")
    }

    onLoad(scene: Scene) {
        super.onLoad(scene)
        this.controlMaterial('alarm_light', (mesh, mat) => {
            this.statusMaterial = mesh.material
        })
    }

    private setColor(color: Color | string | number) {
        (this.statusMaterial as any).color.set(color)
    }

    colorTimer = () => {
        console.log('start color timer')
        this.alarmTimer = setInterval(() => {
            this.changeColor++
            this.changeColor %=2
            if (this.changeColor == 1) {
                this.setColor(0xff0000)
            } else {
                this.setColor(0xffffff)
            }

        }, 1000)
    }

    alarm() {
        this.colorTimer()
        this.status = 3
    }

    private stopAlarm() {
        console.log("stop alarm")
        clearInterval(this.alarmTimer)
    }

    idle() {
        console.log("status -> idle")
        if (this.status == 3) {
            this.stopAlarm()
        }
        this.setColor(0xffffff)
        this.status = 1
    }

    work() {
        console.log("status -> work")
        if (this.status == 3) {
            this.stopAlarm()
        }
        this.setColor(0x00ff00)
        this.status = 2
    }

    clone(recursive?: boolean): this {
        let obj = super.clone(recursive) as this
        obj.statusMaterial = this.statusMaterial
        return obj
    }
}